package com.adv.ems.filters.original.after;

import cn.hutool.json.JSONUtil;
import com.adv.ems.constants.EmsConst;
import com.adv.ems.db.entity.SystemConfigDO;
import com.adv.ems.filters.EnergyDataBaseFilter;
import com.adv.ems.filters.dto.FilterParam;
import com.adv.ems.filters.original.dto.OriginalDealAfterDTO;
import com.adv.ems.manager.SystemConfigManager;
import com.adv.ems.model.dto.OriginalDataDealConfigDTO;
import com.adv.ems.model.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Component
public class UpdateLastIdAfterFilter extends EnergyDataBaseFilter<OriginalDealAfterDTO, Boolean> {
    @Resource
    SystemConfigManager systemConfigManager;

    @Override
    protected String getFilterName() {
        return "更新最后一次处理原始数据ID";
    }

    @Override
    protected double getOrder() {
        return 0.5;
    }

    @Override
    protected boolean isBefore() {
        return false;
    }

    @Override
    protected String getType() {
        return OriginalDealAfterDTO.class.getName();
    }

    @Override
    protected ResultVO<Boolean> handle(FilterParam<OriginalDealAfterDTO> param) {
        OriginalDealAfterDTO result = param.getList().get(0);
        OriginalDataDealConfigDTO config = result.getConfig();
        if (config.getLastId() >= result.getToId()) {
            log.warn("原始数据最后ID【old：{}，new：{}】记录异常", result.getToId(), config.getLastId());
            return ResultVO.success();
        }
        config.setLastId(result.getToId());
        SystemConfigDO record = new SystemConfigDO();
        record.setId(config.getSystemConfigId());
        record.setValue(JSONUtil.toJsonStr(config));
        record.setUpdateTime(new Date());
        if (config.getSystemConfigId() == null) {
            record.setCode(EmsConst.SystemConfigKey.SYSTEM_CONFIG_ORIGINAL_DATA_DEAL_CONFIG_KEY);
            record.setName(config.getConfigName());
            record.setType(EmsConst.SystemConfigKey.SYSTEM_CONFIG_ORIGINAL_DATA_DEAL_CONFIG_KEY);
            record.setCreateTime(new Date());
            systemConfigManager.saveData(record);
            config.setSystemConfigId(record.getId());
        }else {
            systemConfigManager.updateDataById(record);
        }
        return ResultVO.success();
    }
}
